﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.Diagnostics;

namespace xReplace
{
    class CmdRunCommand : AbstractProcessingCommand
    {
        public CmdRunCommand(ref Content pipes)
            : base(ref pipes)
        {}


        public override bool ProcessCommand(System.Xml.XmlNodeList param)
        {
            StreamReader outputReader = null;
            StreamReader errorReader = null;

            string toLabel = this.GetNodeValue("tolabel", param);
            string fromLabel = this.GetNodeValue("fromlabel", param);

            string exec = this.GetNodeValue("filename", param);
            string args = this.GetNodeValue("arguments", param);

            string tmp = "";
            if ((fromLabel != "") && (this.NodeExists("fromlabel", param)))
                tmp = this.contentPipelines.LoadContent(fromLabel);
            else
                tmp = args;


            Process p = new Process();
            p.StartInfo = new ProcessStartInfo();
            p.StartInfo.FileName = exec;
            p.StartInfo.Arguments = tmp;

            p.StartInfo.ErrorDialog = false;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;

            bool processStarted = p.Start();
            if (processStarted)
            {
                //Get the output stream
                outputReader = p.StandardOutput;
                errorReader = p.StandardError;
                p.WaitForExit();

                //Display the result
                string displayText = outputReader.ReadToEnd();
                //displayText += errorReader.ReadToEnd();
                this.contentPipelines.StoreContent(toLabel, displayText);
            }            
            
            // Read the output stream first and then wait.
            try
            {
                outputReader.Close();
                outputReader.Dispose();
                errorReader.Close();
                errorReader.Dispose();
            }
            catch (Exception ex)
            { 
            
            }    
            return true;
        }
    }
}
